<template>
  <div>
    <el-card class="user_card1">
      <el-form :inline="true" class="user_form">
        <el-form-item label="用户名">
          <el-input
            v-model="keyWord"
            placeholder="请你输入搜索用户名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" :disabled="!keyWord">搜索</el-button>
          <el-button @click="reset" type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="user_card2">
      <el-button type="primary" @click="addUser" v-has="`btn.User.add`">
        添加用户
      </el-button>
      <el-button
        @click="deleteSelectUser"
        type="danger"
        :disabled="!selectIdArr.length"
      >
        批量删除
      </el-button>
      <!-- 表格展示用户信息 -->
      <el-table
        @selection-change="selectChange"
        v-loading="loading"
        :data="userArr"
        class="user_table"
        :border="true"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column prop="id" label="ID" align="center"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名字"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="用户名称"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="用户角色"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="320">
          <template #="{ row }">
            <el-button @click="setRole(row)" type="primary" icon="User">
              分配角色
            </el-button>
            <el-button @click="updateUser(row)" type="primary" icon="Edit">
              编辑
            </el-button>
            <el-popconfirm
              @confirm="deleteUser(row.id)"
              :title="`你确定要删除${row.username}?`"
            >
              <template #reference>
                <el-button type="danger" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9]"
        layout="prev, pager, next, jumper,-> , sizes, total"
        :total="total"
        @size-change="handler"
        @current-change="getHasUser"
      />
    </el-card>
    <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
    <el-drawer
      v-model="drawer"
      :title="userParams.id ? '更新用户' : '添加用户'"
    >
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item prop="username" label="用户姓名">
          <el-input
            v-model="userParams.username"
            placeholder="请你输入用户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="name" label="用户昵称">
          <el-input
            v-model="userParams.name"
            placeholder="请你输入用户昵称"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!userParams.id" prop="password" label="用户密码">
          <el-input
            v-model="userParams.password"
            placeholder="请你输入用户密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-drawer>
    <!-- 抽屉结构:用于某一个已有的账号进行职位分配 -->
    <el-drawer v-model="drawer1" title="分配角色">
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            @change="handleCheckAllChange"
            v-model="checkAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="index"
              :label="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button @click="confirmClick" type="primary">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import {
  reqSelectUser,
  reqRemoveUser,
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
} from "@/api/acl/user";
import type {
  SetRoleData,
  UserResponseData,
  Records,
  User,
  AllRoleResponseData,
  AllRole,
} from "@/api/acl/user/type";
import { ElMessage } from "element-plus";
import useLayOutSettingStore from "@/store/modules/setting";
let layOutSettingStore = useLayOutSettingStore();
//分页器当前页码
let pageNo = ref<number>(1);
//每一页展示几条数据
let pageSize = ref<number>(5);
let total = ref<number>(0);
// 存储全部用户的数组
let userArr = ref<Records>([]);
// 判断数据是否全部请求完毕
let loading = ref<boolean>(false);
// 控制抽屉的显示与隐藏
const drawer = ref<boolean>(false);
// 控制抽屉的显示与隐藏
const drawer1 = ref<boolean>(false);
// 获取formRef组件实例
let formRef = ref();
// 存储全部职位的数据
let allRole = ref<AllRole>([]);
// 当前用户已有的职位
let userRole = ref<AllRole>([]);
// 准备一个数据存储批量删除的用户的ID
let selectIdArr = ref<User[]>([]);
// 收集用户信息的响应式数据
let keyWord = ref<string>("");

// 收集用户信息的响应式数组
let userParams = reactive<User>({
  username: "",
  name: "",
  password: "",
});

// 表单校验的规则对象
const rules = {
  username: [
    { required: true, message: "用户名不能为空！", trigger: "blur" },
    {
      required: true,
      min: 5,
      max: 8,
      message: "用户名输入至少五位，最多八位！",
      trigger: "blur",
    },
  ],
  name: [
    { required: true, message: "昵称不能为空！", trigger: "blur" },
    {
      required: true,
      min: 5,
      max: 8,
      message: "昵称输入至少五位，最多八位！",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "密码不能为空！", trigger: "blur" },
    {
      required: true,
      min: 6,
      max: 10,
      message: "密码输入至少六位，最多十位！",
      trigger: "blur",
    },
  ],
};

// 组件挂载完毕
onMounted(() => {
  getHasUser();
});
// 获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
  loading.value = await true;
  // 收集当前页码
  pageNo.value = pager;
  let result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyWord.value,
  );
  if (result.code === 200) {
    total.value = result.data.total;
    userArr.value = result.data.records;
  }

  loading.value = await false;
};
// 分页器下拉菜单的自定义事件回调
const handler = () => {
  getHasUser();
};
// 添加用户按钮的回调
const addUser = () => {
  Object.assign(userParams, {
    id: 0,
    username: "",
    name: "",
    password: "",
  });
  nextTick(() => {
    formRef.value?.clearValidate(["username", "name", "password"]);
  });
  drawer.value = true;
};
// 更新用户按钮的回调
const updateUser = (row: User) => {
  drawer.value = true;
  // 存储收集已有的账号信息
  Object.assign(userParams, row);
};
// 保存按钮的回调
const save = async () => {
  await formRef.value.validate(async (valid: any) => {
    if (valid) {
      //保存按钮:添加新的用户|更新已有的用户账号信息
      let result: any = await reqAddOrUpdateUser(userParams);
      if (result.code === 200) {
        // 提示信息
        ElMessage({
          type: "success",
          message: userParams.id ? "更新成功" : "添加成功",
        });
        getHasUser(userParams.id ? pageNo.value : 1);
        // 浏览器自动刷新一次
        // window.location.reload();
      } else {
        ElMessage({
          type: "error",
          message: userParams.id ? "更新失败" : "添加失败",
        });
      }
      drawer.value = false;
    }
  });
};
// 取消按钮的回调
const cancel = () => {
  drawer.value = false;
};
// 分配角色按钮的回调
const setRole = async (row: User) => {
  //存储已有的用户信息
  Object.assign(userParams, row);
  //获取全部的职位的数据与当前用户已有的职位的数据
  let result: AllRoleResponseData = await reqAllRole(userParams.id as number);
  if (result.code == 200) {
    //存储全部的职位
    allRole.value = result.data.allRolesList;
    //存储当前用户已有的职位
    userRole.value = result.data.assignRoles;
    //抽屉显示出来
    drawer1.value = true;
  }
};

//收集顶部复选框全选数据
const checkAll = ref<boolean>(false);
//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true);
//顶部的全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  //val:true(全选)|false(没有全选)
  userRole.value = val ? allRole.value : [];
  //不确定的样式(确定样式)
  isIndeterminate.value = false;
};
//顶部全部的复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
  //顶部复选框的勾选数据
  //代表:勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
  checkAll.value = value.length === allRole.value.length;
  //不确定的样式
  isIndeterminate.value = value.length !== allRole.value.length;
};
//确定按钮的回调(分配职位)
const confirmClick = async () => {
  //收集参数
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => item.id as number),
  };
  //分配用户的职位
  let result: any = await reqSetUserRole(data);
  if (result.code == 200) {
    //提示信息
    ElMessage({ type: "success", message: "分配职务成功" });
    //关闭抽屉
    drawer1.value = false;
    //获取更新完毕用户的信息,更新完毕留在当前页
    getHasUser(pageNo.value);
  }
};
// 删除某一个用户
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};
//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
  selectIdArr.value = value;
  console.log(selectIdArr.value);
};
//批量删除按钮的回调
const deleteSelectUser = async () => {
  //整理批量删除的参数
  let idsList: any = selectIdArr.value.map((item) => {
    return item.id;
  });
  //批量删除的请求
  let result: any = await reqSelectUser(idsList);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};
//搜索按钮的回调
const search = () => {
  //根据关键字获取相应的用户数据
  getHasUser();
  //清空关键字
  nextTick(() => {
    keyWord.value = "";
  });
};
//重置按钮
const reset = () => {
  layOutSettingStore.refsh = !layOutSettingStore.refsh;
};
</script>
<style scoped lang="scss">
.user_card1 {
  margin-bottom: 16px;

  .user_form {
    display: flex;
    justify-content: space-between;

    .el-form-item {
      margin: 0;
    }
  }
}

.user_card2 {
  .user_table {
    margin: 16px 0;
  }
}
</style>
